package com.union.vehicleassistant.util;

import android.util.Base64;


import com.union.vehicleassistant.common.Constant;

import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * Created by MSI-NB on 2021-6-8.
 */

public class RsaUtilsBase {
    /**
     * @params str 要加密的字符串
     */
    public static String rsaEncode(String str) {
        String outStr = "";
        try {
            // base64编码的公钥
            byte[] decoded = Base64.decode(Constant.RSA_PUBLIC_KEY, Base64.DEFAULT);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            // RSA加密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            outStr = Base64.encodeToString(cipher.doFinal(str.getBytes("UTF-8")), Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outStr;
    }
}
